<template>
  <div class="live">
    <div class="live-right">
      <el-input prefix-icon="el-icon-search" placeholder="搜索用户" v-model="keywords"></el-input>
      <div class="peer-list">
        <div class="peer-user" v-for="item in onlineUsers" :key="item.id">
          <div class="peer-info">
            <img class="avatar" :src="baseURL+item.avatar"/>
            <div>
              <div class="name">{{ item.nickname }}</div>
              <!--              <div class="time">在线时长：45分钟</div>-->
            </div>
          </div>
          <el-dropdown v-if="!item.is_muted" placement="bottom-start" @command="(e)=>muted(e,item)">
            <el-button type="danger">禁言</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="1">1小时</el-dropdown-item>
                <el-dropdown-item :command="2">2小时</el-dropdown-item>
                <el-dropdown-item :command="3">3小时</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button v-else @click="unmuted(item)">取消禁言</el-button>
        </div>
      </div>
    </div>
    <div class="live-left">
      <div class="header">
        <div class="title">直播间实时监控</div>
        <div class="online">在线人数：{{ originOnlineUsers.length }}</div>
      </div>
      <div class="message-content">
        <div class="peer-user" v-for="(item,index) in msgs" :key="index">
          <template v-if="item.nickname==='System'">
            <div class="system">
              <span>{{ item.content }}</span>
            </div>
          </template>
          <template v-else>
            <img class="avatar" :src="baseURL+item.avatar"/>
            <div>
              <div class="peer-info">
                <div class="name">{{ item.nickname }}</div>
                <div class="time">{{ item.time }}</div>
                <!--              <el-tag class="level">Lv5</el-tag>-->
              </div>
              <div class="msg">{{ item.content }}</div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import {ElMessageBox, ElMessage} from "element-plus"
import moment from 'moment'
import {groupOnlineUserApi, courseDetailApi, groupMuteApi, unGroupMuteApi} from "@/api/course"
import {useUserStore} from "@/stores/user"
import {sendMessage} from "@/utils/message"
import bus from "@/utils/bus"

const route = useRoute()

const baseURL = ref(import.meta.env.VITE_APP_API_URL)

const onlineUsers = ref([])
const originOnlineUsers = ref([])

const groupUuid = ref()

const liveId = route.query.live
const msgs = ref([])
const keywords = ref("")

const {userInfo} = storeToRefs(useUserStore())

const joinRoom = () => {
  sendMessage(JSON.stringify({
    from: userInfo.value.uuid,
    to: groupUuid.value,
    avatar: userInfo.value.avatar,
    fromUser: userInfo.value.nickname,
    action: "join",
    contentType: 1,
    messageType: 3
  }))
}

const leaveRoom = () => {
  sendMessage(JSON.stringify({
    from: userInfo.value.uuid,
    to: groupUuid.value,
    avatar: userInfo.value.avatar,
    fromUser: userInfo.value.nickname,
    action: "leave",
    contentType: 1,
    messageType: 3
  }))
}

const getOnlineUser = () => {
  courseDetailApi(liveId).then((courseRes) => {
    courseRes.data.chat_group_info && groupOnlineUserApi({group_uuid: courseRes.data.chat_group_info.group_uuid}).then((res) => {
      onlineUsers.value = [...(res.data || [])]
      originOnlineUsers.value = [...(res.data || [])]
      groupUuid.value = courseRes.data.chat_group_info.group_uuid

      joinRoom()
    })
  })
}

const onMessage = () => {
  bus.on("onmessage", (data) => {
    if (data.messageType !== 3) return

    const fun = {
      join: () => {
        msgs.value.push({
          nickname: data.from,
          avatar: data.avatar,
          content: data.content,
          time: moment(moment.now()).format("HH:mm")
        })
      },
      leave: () => {
        msgs.value.push({
          nickname: data.from,
          avatar: data.avatar,
          content: data.content,
          time: moment(moment.now()).format("HH:mm")
        })
      },
      send: () => {
        msgs.value.push({
          nickname: data.fromUser,
          avatar: data.avatar,
          content: data.content,
          time: moment(moment.now()).format("HH:mm")
        })
        setTimeout(() => {
          scrollToBottom()
        }, 100)
      }
    }
    fun[data.action] && fun[data.action]()
  })
}

const muted = (e, item) => {
  ElMessageBox.confirm(`确定将${item.nickname}禁言${e}小时吗？`, '提示').then(() => {
    const now = moment.now()
    const end = moment().add(e, "h")
    groupMuteApi({
      group_uuid: groupUuid.value,
      user_uuid: item.uuid,
      start_at: moment(now).format('YYYY-MM-DD HH:mm:ss'),
      end_at: moment(end).format('YYYY-MM-DD HH:mm:ss')
    }).then(() => {
      ElMessage.success("禁言成功")
      getOnlineUser()
    })
  })
}

const unmuted = (item) => {
  ElMessageBox.confirm(`确定将${item.nickname}解除禁言吗？`, '提示').then(() => {
    unGroupMuteApi({group_uuid: groupUuid.value, user_uuid: item.uuid}).then(() => {
      ElMessage.success("取消禁言成功")
      getOnlineUser()
    })
  })
}

onMounted(() => {
  getOnlineUser()
  onMessage()
})

onUnmounted(() => {
  leaveRoom()
})

const scrollToBottom = () => {
  const messageContent = document.querySelector('.message-content')
  if (messageContent) {
    messageContent.scroll({
      top: messageContent.scrollHeight,
      behavior: 'smooth'
    })
  }
}

watch(() => keywords.value, (val) => {
  if (val) {
    onlineUsers.value = [...originOnlineUsers.value.filter(item => item.nickname.indexOf(val) !== -1)]
  } else {
    onlineUsers.value = [...originOnlineUsers.value]
  }
})
</script>

<style lang="scss" scoped>
.live {
  width: 100%;
  height: 100%;
  padding: 20px;
  background: #f0f2f5;

  .avatar {
    display: block;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    flex-shrink: 0;
  }

  .name {
    font-size: 16px;
    color: #333;
    font-weight: bold;
  }

  .live-right {
    float: right;
    width: 316px;
    height: 100%;
    border-radius: 8px;
    background: #fff;
    padding: 20px;

    .peer-list {
      margin-top: 20px;
      height: calc(100% - 56px);
      overflow-y: auto;
    }

    .peer-user {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .peer-info {
        display: flex;
        align-items: center;
        gap: 10px;

        .time {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }

  .live-left {
    height: 100%;
    margin-right: 336px;
    border-radius: 8px;
    background: #fff;
    padding: 20px;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;

      .title {
        font-size: 18px;
        color: #333;
        font-weight: bold;
      }

      .online {
        font-size: 16px;
        color: #666;
      }
    }

    .message-content {
      height: calc(100% - 67px);
      overflow-y: auto;
    }

    .peer-user {
      display: flex;
      gap: 10px;
      margin-bottom: 20px;

      .system {
        flex: 1;
        text-align: center;
        margin: 12px 0;

        span {
          color: #000;
          background: rgba(0, 0, 0, 0.1);
          padding: 8px 20px;
          border-radius: 40px;
        }
      }

      .peer-info {
        display: flex;
        gap: 8px;
        align-items: center;

        .time {
          font-size: 12px;
          color: #999;
        }

        .level {
          font-size: 12px;
        }
      }

      .msg {
        font-size: 14px;
        color: #666;
      }
    }
  }
}
</style>
